package com.wangzhenyu.common.view.dialog

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import com.wangzhenyu.common.util.exts.show
import com.wangzhenyu.common.R

@Suppress("UNUSED")
class LoadingDialog : Dialog {

    private var loadingMsgTv: TextView? = null

    constructor(context: Context) : super(context)
    constructor(context: Context, themeResId: Int) : super(context, themeResId)

    fun setLoadingText(content: String?) {
        if (loadingMsgTv == null) {
            val rootView = window?.decorView
            if (rootView != null) {
                loadingMsgTv = findViewById(R.id.tipTextView)
            }
        }
        if (loadingMsgTv != null) {
            loadingMsgTv?.show(!TextUtils.isEmpty(content))
            loadingMsgTv?.text = content
        }
    }

    //构建Dialog
    class Builder(private val context: Context) {
        private var isCancelable = false
        private var isCancelOutside = false

        /**
         * 设置是否可以按返回键取消
         */
        fun setCancelable(isCancelable: Boolean): Builder {
            this.isCancelable = isCancelable
            return this
        }

        /**
         * 设置是否可以点击外部取消
         */
        fun setCancelOutside(isCancelOutside: Boolean): Builder {
            this.isCancelOutside = isCancelOutside
            return this
        }

        @SuppressLint("InflateParams")
        fun create(): LoadingDialog {
            val inflater = LayoutInflater.from(context)
            val view: View = inflater.inflate(R.layout.dialog_loading, null)
            val loading = LoadingDialog(context, R.style.LoadingDialogStyle)
            loading.setContentView(view)
            loading.setCancelable(isCancelable)
            loading.setCanceledOnTouchOutside(isCancelOutside)
            loading.window?.setType(WindowManager.LayoutParams.TYPE_APPLICATION)
            //实现loading的透明度
            val lp: WindowManager.LayoutParams? = loading.window?.getAttributes()
            lp?.alpha = 0.6f
            loading.window?.setAttributes(lp)
            return loading
        }
    }
}
